package com.itgone.presenter.impl;

import android.app.Activity;

import com.github.lazylibrary.util.AppUtils;
import com.github.lazylibrary.util.ShellUtils;
import com.github.lazylibrary.util.StringUtils;
import com.github.lazylibrary.util.ToastUtils;
import com.itgone.bean.User;
import com.itgone.common.Const;
import com.itgone.common.ServerResponse;
import com.itgone.model.IUserModel;
import com.itgone.model.impl.UserModelImpl;
import com.itgone.presenter.ILoginPresenter;
import com.itgone.util.AppUtil;
import com.itgone.util.JsonUtil;
import com.itgone.util.SPUtil;
import com.itgone.view.ILoginView;
import com.itgone.view.activity.MainActivity;
import com.zhy.http.okhttp.callback.StringCallback;

import java.net.SocketTimeoutException;

import okhttp3.Call;
import okhttp3.Request;

public class LoginPresenterImpl implements ILoginPresenter {

    private IUserModel iUserModel = new UserModelImpl();
    private ILoginView loginView;

    public LoginPresenterImpl(ILoginView loginView) {
        this.loginView = loginView;
    }

    @Override
    public void doLogin() {
        final String username = loginView.getUsername();
        final String password = loginView.getPassword();

        if (StringUtils.isBlank(username)) {
            loginView.setUnError("用户名不能为空");
            return;
        }
        if (StringUtils.isBlank(password)) {
            loginView.setPwdError("密码不能为空");
            return;
        }
        iUserModel.login(username, password, new StringCallback() {

            @Override
            public void onBefore(Request request, int id) {
                System.out.println("onBefore " + id);
                loginView.setProgress(true);
            }

            @Override
            public void onAfter(int id) {
                System.out.println("onAfter " + id);
                loginView.setProgress(false);
            }


            @Override
            public void onError(Call call, Exception e, int id) {
                if (e instanceof SocketTimeoutException) {
                    ToastUtils.showToast(AppUtil.getContext(), "服务器链接超时，请稍后再试");
                } else {
                    ToastUtils.showToast(AppUtil.getContext(), e.toString());
                }
            }

            @Override
            public void onResponse(String response, int id) {
                System.out.println("onResponse " + response);
                ServerResponse loginResponse = JsonUtil.parseResponse(response, User.class);
                if (loginResponse.isSuccess()) {
                    loginView.showDialog("登陆成功");
//                    SPUtil.put(Const.KEY_USERNAME, username);
//                    SPUtil.put(Const.KEY_PASSWORD, password);

                    AppUtil.openActivity(MainActivity.class);
                    AppUtil.finishActivity((Activity) loginView);
                } else {
                    loginView.showDialog(loginResponse.getMsg());
                }
            }
        });
    }
}
